/**
 * Copyright (C) 2018-2022
 * All rights reserved, Designed By www.yixiang.co
 */
package co.yixiang.modules.activity.rest;
import com.google.common.collect.Lists;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import co.yixiang.api.YshopException;
import co.yixiang.enums.CouponEnum;
import co.yixiang.modules.activity.domain.YxStoreCoupon;
import co.yixiang.modules.activity.param.YxStoreCouponParam;
import co.yixiang.modules.activity.service.YxStoreCouponService;
import co.yixiang.modules.activity.service.YxStoreCouponUserService;
import co.yixiang.modules.activity.service.dto.YxStoreCouponQueryCriteria;
import co.yixiang.modules.activity.vo.CouponSelectProductVo;
import co.yixiang.modules.aop.ForbidSubmit;
import co.yixiang.modules.logging.aop.log.Log;
import co.yixiang.utils.SecurityUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hupeng
 * @date 2019-11-09
 */
@Api(tags = "商城:优惠券管理")
@RestController
@RequestMapping("api")
public class StoreCouponController {

    private final YxStoreCouponService yxStoreCouponService;
    @Autowired
    private YxStoreCouponUserService storeCouponUserService;

    public StoreCouponController(YxStoreCouponService yxStoreCouponService) {
        this.yxStoreCouponService = yxStoreCouponService;
    }

    @Log("查询")
    @ApiOperation(value = "查询")
    @GetMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_SELECT')")
    public ResponseEntity getYxStoreCoupons(YxStoreCouponQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(yxStoreCouponService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("新增")
    @ApiOperation(value = "新增")
    @PostMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_CREATE')")
    public ResponseEntity create(@Validated @RequestBody YxStoreCouponParam couponParam) throws JsonProcessingException {
        YxStoreCoupon yxStoreCoupon = new YxStoreCoupon();
        String productIdJson = null;
        //校验优惠券
        this.checkStoreCoupon(couponParam);
        if (CouponEnum.LIMIT_TYPE_2.getValue().equals(couponParam.getLimitType())) {
            List<CouponSelectProductVo> selectProductList = couponParam.getSelectProductList();
            ObjectMapper objectMapper = new ObjectMapper();
            productIdJson = objectMapper.writeValueAsString(selectProductList);

        }
        BeanUtil.copyProperties(couponParam, yxStoreCoupon, "selectProductList");
        if (StrUtil.isNotEmpty(productIdJson)) {
            yxStoreCoupon.setProductIdJson(productIdJson);
        }
        List<Integer> cateList = couponParam.getCateList();
        if (cateList != null && cateList.size() > 0) {
            String commaSeparatedString = cateList.stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(","));
            yxStoreCoupon.setCateIds(commaSeparatedString);
        }
        yxStoreCoupon.setUpdateTime(new Date());
        yxStoreCoupon.setUpdateBy(SecurityUtils.getUsername());
        return new ResponseEntity<>(yxStoreCouponService.save(yxStoreCoupon), HttpStatus.CREATED);
    }

    @Log("修改")
    @ApiOperation(value = "修改")
    @PutMapping(value = "/yxStoreCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_EDIT')")
    public ResponseEntity update(@Validated @RequestBody YxStoreCouponParam couponParam) throws JsonProcessingException {
        YxStoreCoupon yxStoreCoupon = new YxStoreCoupon();
        String productIdJson = null;
        //校验优惠券
        this.checkStoreCoupon(couponParam);
        if (CouponEnum.LIMIT_TYPE_2.getValue().equals(couponParam.getLimitType())) {
            List<CouponSelectProductVo> selectProductList = couponParam.getSelectProductList();
            ObjectMapper objectMapper = new ObjectMapper();
            productIdJson = objectMapper.writeValueAsString(selectProductList);

        }
        BeanUtil.copyProperties(couponParam, yxStoreCoupon, "selectProductList");
        if (StrUtil.isNotEmpty(productIdJson)) {
            yxStoreCoupon.setProductIdJson(productIdJson);
        }
        List<Integer> cateList = couponParam.getCateList();
        if (cateList != null && cateList.size() > 0) {
            String commaSeparatedString = cateList.stream()
                    .map(Object::toString)
                    .collect(Collectors.joining(","));
            yxStoreCoupon.setCateIds(commaSeparatedString);
        }
        yxStoreCoupon.setUpdateTime(new Date());
        yxStoreCoupon.setUpdateBy(SecurityUtils.getUsername());
        yxStoreCouponService.saveOrUpdate(yxStoreCoupon);
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @Log("复制优惠券")
    @ApiOperation(value = "复制优惠券")
    @PostMapping(value = "/yxStoreCoupon/copyCoupon")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_CREATE')")
    public ResponseEntity copyCoupon( @RequestBody JSONObject jSONObject) throws JsonProcessingException {
        Integer cid = jSONObject.getInt("cid");
        YxStoreCoupon yxStoreCoupon = yxStoreCouponService.getById(cid);
        if(yxStoreCoupon == null){
            throw new YshopException("优惠券不存在，请检查");
        }
        YxStoreCoupon copyCoupon = new YxStoreCoupon();
        copyCoupon.setTitle("【复制】"+yxStoreCoupon.getTitle());
        copyCoupon.setIntegral(yxStoreCoupon.getIntegral());
        copyCoupon.setCouponPrice(yxStoreCoupon.getCouponPrice());
        copyCoupon.setUseMinPrice(yxStoreCoupon.getUseMinPrice());
        copyCoupon.setCouponTime(yxStoreCoupon.getCouponTime());
        copyCoupon.setSort(yxStoreCoupon.getSort());
        copyCoupon.setStatus(1);
        copyCoupon.setType(yxStoreCoupon.getType());
        copyCoupon.setProductId(yxStoreCoupon.getProductId());
        copyCoupon.setIsLimitCate(yxStoreCoupon.getIsLimitCate());
        copyCoupon.setLimitType(yxStoreCoupon.getLimitType());
        copyCoupon.setLimitGoodCateNum(yxStoreCoupon.getLimitGoodCateNum());
        copyCoupon.setCateIds(yxStoreCoupon.getCateIds());
        copyCoupon.setCateList(yxStoreCoupon.getCateList());
        copyCoupon.setProductIdJson(yxStoreCoupon.getProductIdJson());
        copyCoupon.setCreateTime(new Date());
        yxStoreCoupon.setUpdateTime(new Date());
        yxStoreCoupon.setUpdateBy(SecurityUtils.getUsername());
        copyCoupon.setIsDel(0);
        return new ResponseEntity<>(yxStoreCouponService.save(copyCoupon), HttpStatus.CREATED);
    }


    private void checkStoreCoupon(YxStoreCouponParam couponParam) {
        if (couponParam.getCouponPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new YshopException("优惠券面额要大于0");
        }
        //通用券0,商品券1
        if (CouponEnum.TYPE_0.getValue().equals(couponParam.getType())) {
            //	限制类型，1限制金额2限制商品数量3限制商品分类
            if (CouponEnum.LIMIT_TYPE_1.getValue().equals(couponParam.getLimitType())) {
                if (couponParam.getUseMinPrice().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new YshopException("最低消费金额要大于0");
                }
            } else if (CouponEnum.LIMIT_TYPE_2.getValue().equals(couponParam.getLimitType())) {
                if (couponParam.getLimitGoodsNum() == null) {
                    throw new YshopException("请输入限制商品数量");
                }
                if (couponParam.getLimitGoodsNum() == 0) {
                    throw new YshopException("请输入限制商品数量大于0");
                }
            }
        } else if (CouponEnum.TYPE_1.getValue().equals(couponParam.getType())) {
            if (StrUtil.isEmpty(couponParam.getProductId()) && !CouponEnum.LIMIT_TYPE_3.getValue().equals(couponParam.getLimitType())) {
                throw new YshopException("请选择商品");
            }
            //	限制类型，1限制金额2限制商品数量3限制商品分类
            if (CouponEnum.LIMIT_TYPE_1.getValue().equals(couponParam.getLimitType())) {
                if (couponParam.getUseMinPrice().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new YshopException("最低消费金额要大于0");
                }
            } else if (CouponEnum.LIMIT_TYPE_2.getValue().equals(couponParam.getLimitType())) {
                List<CouponSelectProductVo> selectProductList = couponParam.getSelectProductList();
                for (CouponSelectProductVo couponSelectProduct : selectProductList) {
                    if (couponSelectProduct.getLimitGoodsNum() == null) {
                        throw new YshopException("请输入" + couponSelectProduct.getStoreName() + "的限制商品数量");
                    }
                }
                Integer isLimitCate = couponParam.getIsLimitCate();
                Integer limitGoodCateNum = couponParam.getLimitGoodCateNum();
                if (isLimitCate == null) {
                    throw new YshopException("请选择是否限制商品分类");
                }
                if (isLimitCate == 1) {
                    List<Integer> cateList = couponParam.getCateList();
                    if (cateList.size() == 0) {
                        throw new YshopException("请选择限制商品分类");
                    }
                    if (limitGoodCateNum == 0) {
                        throw new YshopException("限制最低商品总数要大于0");
                    }
                }
            }else if (CouponEnum.LIMIT_TYPE_3.getValue().equals(couponParam.getLimitType())) {
                List<Integer> cateList = couponParam.getCateList();
                if (cateList.size() == 0) {
                    throw new YshopException("请选择限制商品分类");
                }
            }
        }
    }

    @ForbidSubmit
    @Log("删除")
    @ApiOperation(value = "删除")
    @DeleteMapping(value = "/yxStoreCoupon/{id}")
    @PreAuthorize("@el.check('admin','YXSTORECOUPON_ALL','YXSTORECOUPON_DELETE')")
    public ResponseEntity delete(@PathVariable Integer id) {
        yxStoreCouponService.removeById(id);
        return new ResponseEntity(HttpStatus.OK);
    }
}
